layui.use(['jquery','layer','table','form'],function(){
    var $=layui.jquery;
    var layer=layui.layer;
    var table=layui.table;
    var form=layui.form;
    var user = JSON.parse(localStorage.getItem('user'));
    var userId = user.data.userId;
    judge();
    demoTable();
    function judge(){
        $.ajax({
            url: '/product/judgePower',
            type: 'post',
            dataType: 'json',
            data: {'id':userId},
            success: function (data) {
                var power = false;
                var dat = data.data;
                for (var i = 0; i < dat.length; i++) {
                    if(dat[i] == 1){
                        power = true;
                    }
                }
                if(power){
                    demoZtree();
                }else{
                    demoZtreeOther();
                }
            }
        })
    }
    $.ajax({
        url: '/product/getProductCategroys',
        dataType: 'json',
        type: 'post',
        success: function (data) {
            var ProductCategroys = data.data;
            for (var i = 0; i < ProductCategroys.length; i++) {
                $('#title').append('<option value="' + ProductCategroys[i].title + '" >' + ProductCategroys[i].title + '</option>')
            }
            form.render('select');
        }
    });
    //刷新
    $('#refresh').click(function () {
        location.reload();
    })
    function demoZtree(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable:false,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onRightClick: OnRightClick,
                beforeRename: beforeRename,
                onClick:zTreeOnClick
            }
        };

        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        //修改前判断
        function beforeRename(treeId, treeNode, newName) {
            if (newName.length == 0) {
                alert("节点名称不能为空.");
                var zTree = $.fn.zTree.getZTreeObj("demoTree");
                setTimeout(function(){zTree.editName(treeNode)}, 10);
                return false;
            }
            return true;
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }

            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }
        //添加树节点
        addTreeNode = function addTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var parentId = nodes[0].categroyId;
            layer.open({
                type:1,
                title:"添加节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>添加分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='商品分类'>"
                    +"</div>"+"</div></form>",
                btn:['添加','取消'],
                yes:function () {
                    var title = $("#addNode").val();
                    if(title.length != 0){
                        $.ajax({
                            url: '/product/addProductTree',
                            type: 'post',
                            dataType: 'json',
                            data: {'parentId':parentId,'title':title},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }
        //删除树节点
        removeTreeNode = function removeTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var categroyId = nodes[0].categroyId;
            var node = nodes[0];
            var count = getProductTreeCount(categroyId);
            if(count > 0){
                layer.msg('此分类下还有商品 不能删除');
                return;
            }
            if(node.isParent){
                layer.msg('此分类下还有商品分类 不能删除');
            }else{
                var layerIndex = layer.confirm('确定要删除吗?', {
                    btn: ['确定','取消'],
                    title: '删除商品分类',
                }, function(){
                    $.ajax({
                        url: '/product/deleteProductTree',
                        type: 'post',
                        dataType: 'json',
                        data: {'categroyId':categroyId},
                        success: function (data) {
                            if(data.data){
                                zTree.removeNode(nodes[0]);
                                layer.msg("删除成功")
                            }
                        }
                    });
                    layer.close(layerIndex);
                });
            }
        }
        function getProductTreeCount(categroyId){
            var productCount;
            $.ajax({
                url: '/product/getProductTreeCount',
                type: 'post',
                dataType: 'json',
                async: false,
                data: {'categroyId':categroyId},
                success: function (data) {
                    if(data.data > 0){
                        productCount = data.data;
                    };
                }
            });
            return productCount;
        };
        //修改树节点
        edit = function edit() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var categroyId = nodes[0].categroyId;
            layer.open({
                type:1,
                title:"修改节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>修改分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='商品分类'>"
                    +"</div>"+"</div></form>",
                btn:['修改','取消'],
                yes:function () {
                    var title = $("#updateNode").val();
                    if(title.length != 0){
                        $.ajax({
                            url: '/product/updateProductTree',
                            type: 'post',
                            dataType: 'json',
                            data: {'title':title,'categroyId':categroyId},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }
        //点击节点，展示对应类别下商品信息
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            categroyId = node.categroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/product/getCheckedProduct',
                    type: 'post',
                    dataType: 'json',
                    data: {'categroyId':categroyId,'result':1,'type':3},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //加载树
        var zTree, rMenu;
        $(document).ready(function(){
            $.ajax({
                url: '/product/getProductTree',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    zTree = $.fn.zTree.init($("#demoTree"), setting, data.data);//初始化树
                    zTree.expandAll(true);    //true 节点全部展开、false节点收缩
                }
            })
            rMenu = $("#rMenu");
        });
    }
    function demoZtreeOther(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onClick:zTreeOnClick
            }
        };
        //点击节点，展示对应类别下商品信息
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            categroyId = node.categroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/product/getCheckedProduct',
                    type: 'post',
                    dataType: 'json',
                    data: {'categroyId':categroyId,'result':1,'type':3},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //加载树
        var zTree, rMenu;
        $(document).ready(function(){
            $.ajax({
                url: '/product/getProductTree',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    zTree = $.fn.zTree.init($("#demoTree"), setting, data.data);//初始化树
                    zTree.expandAll(true);    //true 节点全部展开、false节点收缩
                }
            })
        });
    }
    //导入
    importFile = function importFile(){
        layer.open({
            title:'上传文件',
            type:2,
            area:["400px","300px"],
            btn:["确定","取消"],
            offset: 'auto',
            content:"ImportExcel.html",
        })
    }
    //添加
    addProduct = function addProduct(){
        layer.open({
            title:'添加商品',
            type:2,
            area:['100%','100%'],
            btn:["确定","取消"],
            offset: 'auto',
            content:"/product/productManage/addProduct/add-product.html",
        })
    }
    //高级检索
    $('#advancedSearching').on('click',function () {
        layer.open({
            type: 2,
            title: '高级检索',
            content: ['advanced-search.html','no'],
            area: ['690px', '460px'],
            offset: 'auto',
            shade: 0.4 ,
            resize: false
        })
    });
    //高级检索获取数据
    advancedSearch = function advancedSearch(data){
        demoTable(data);
    }
    //筛选搜索
    $('#search').on('click',function () {
        var productName = $("input[name=productName]").val();
        var title = $("#title option:selected").text();
        var productSate = $("#productSate option:selected").val();
        var productLabel = $("input[name=productLabel]").val();
        getTable(productName,title,productSate,productLabel);
    })
    //获取商品表格数据
    getTable('','','','');
    function getTable(productName,title,productSate,productLabel){
        $.ajax({
            url:"/product/getProductSearch",
            type:"post",
            dataType:"json",
            data:{'productName':productName,'title':title,'productSate':productSate,'productLabel':productLabel,'result':'1','type':3},
            success:function (data) {
                demoTable(data.data);
            }
        })
    }
    //表格渲染
    function demoTable(data) {
        table.render({
            elem: '#demoTable',
            title: "商品列表",
            data: data,
            toolbar: '#tableHeader',
            limit: 10,
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip', 'refresh'],
                limits: [10, 20, 30],
                first: "首页",
                last: "尾页",
            },
            cols: [[
                {type: 'checkbox'},
                {field: "productCode", title: "商品编号", align: 'center'},
                {
                    field: "mainImage", title: "商品图片", align: 'center', templet: function (data) {
                        return '<img src="' + data.mainImage + '"';
                    }
                },
                {field: "productName", title: "商品名称", align: 'center'},
                {
                    field: "currentpriceProduct",
                    title: "商品价格",
                    align: 'center',
                    templet: function (data) {
                        return '<p>￥' + data.currentpriceProduct + '</p>';
                    }
                },
                {
                    field: "productSate", title: "上架/下架", align: 'center', templet: function (data) {
                        if (data.productSate == 1) {
                            return '<input type=\"checkbox\" value="' + data.productId + '" lay-skin=\"switch\" lay-text=\"上架|下架"\ checked lay-filter="switchState">';
                        } else if (data.productSate == 2) {
                            return '<input type=\"checkbox\" value="' + data.productId + '" lay-skin=\"switch\" lay-text=\"上架|下架" lay-filter="switchState"\>';
                        } else if (data.productSate == 3) {
                            return '<p>已删除</p>';
                        }
                    }
                },
                {field: "title", title: "商品分类", align: 'center'},
                {field: "productLabel", title: "商品标签", align: 'center'},
                {
                    field: "result", title: "审核状态", align: 'center', templet: function (data) {
                        return '<p>审核通过</p><p style="color: #00B83F" onclick="productExamine('+data.productId+')">审核详情</p>';
                    }
                },
                {field: '', title: "操作", align: 'center', toolbar: '#table_toolbar'}
            ]]
        })
    }
    //上架/下架商品
    form.on('switch(switchState)', function(data){
        if(data.elem.checked==true){
            $.ajax({
                url:'/product/updateProductState',
                type:'post',
                dataType:'json',
                data:{'productSate':1,'productId':data.value,'updateId':userId},
                success:function (data) {
                    if(data.data){
                        getTable('','','','');
                        layer.msg("修改成功");
                    }
                }
            })
        }else{
            $.ajax({
                url:'/product/updateProductState',
                type:'post',
                dataType:'json',
                data:{'productSate':2,'productId':data.value,'updateId':userId},
                success:function (data) {
                    if(data.data){
                        getTable('','','','');
                        layer.msg("修改成功");
                    }
                }
            })
        }
    })
    //查看商品审核详情
    productExamine = function productExamine(id) {
        localStorage.setItem('courseId',JSON.stringify(id));
        layer.open({
            type:2,
            title:"商品审核详情",
            area:['800px',"500px"],
            btn:["确定","取消"],
            offset:'auto',
            content:"product-examine.html",
            success:function(layero,index){
            }
        })
    }
    //表内操作
    table.on('tool(demoTable)',function (obj) {
        var event = obj.event;
        var productId = obj.data.productId;
        if(event == 'checkTable'){//查看商品详情
            var param = {
                'tableName':'js_product',
                'type':5,
                'userId':userId,
                'remark':'查看反馈统计',
                'logType':1,
            };
            $.ajax({
                url:"/product/addProductLog",
                type:'post',
                dataType:'json',
                data:param,
                success:function (data) {
                    checkTable(productId);
                }
            });
        }else if(event == 'updateTable'){//编辑商品
            $.ajax({
                url: '/product/getProductInformation',
                type: 'post',
                dataType: 'json',
                data: {'type':3,'id':productId},
                success: function (data) {
                    localStorage.setItem('product',JSON.stringify(data.data));
                    var param = {
                        'tableName':'js_product',
                        'type':4,
                        'userId':userId,
                        'remark':'编辑反馈统计',
                        'logType':1,
                    };
                    $.ajax({
                        url:"/product/addProductLog",
                        type:'post',
                        dataType:'json',
                        data:param,
                        success:function (data) {
                        }
                    });
                    layer.open({
                        type:2,
                        title:'修改',
                        area:['800px','600px'],
                        btn:['确定','取消'],
                        offset: 'auto',
                        content:'/product/productManage/productList/product-update.html',
                        yes:function( index,layero){
                            var child = layero.find('iframe').contents();
                            var currentPrice=child.find('input[name=currentpriceProduct]').val();
                            var productName = child.find('input[name=productName]').val();
                            var productSate = child.find("#productSate option:selected").val();
                            var originalpriceProduct = obj.data.currentpriceProduct;
                            var param = {
                                'productId':productId,
                                'productName':productName,
                                'currentpriceProduct':child.find("input[name=currentpriceProduct]").val(),
                                'originalpriceProduct':originalpriceProduct,
                                'productSate':productSate,
                                'productLabel':child.find("input[name=productLabel]").val(),
                                'productDescription':child.find("input[name=productDescription]").val(),
                                'updateId':userId
                            }
                            $.ajax({
                                url:'/product/updateProduct',
                                data:param,
                                type:'post',
                                dataType:'json',
                                success:function (data) {
                                    if(originalpriceProduct != currentPrice){
                                        var params={
                                            'courseId':productId,
                                            'courseName':productName,
                                            'courseStatus':productSate,
                                            'courseCstatus':obj.data.result,
                                            'userId':userId,
                                            'coursePrice':originalpriceProduct,
                                            'courseNprice':currentPrice,
                                            'type':1
                                        }
                                        $.ajax({
                                            url:'/product/addProductJournal',
                                            data:params,
                                            type:'post',
                                            dataType:'json',
                                            success:function (data) {
                                            }
                                        })
                                    }
                                    getTable('','','','');
                                }
                            })
                            layer.close(index);
                        },
                        btn2:function(index,layero){
                            layer.close(index);
                        },
                        end:function () {
                            getTable('','','','');
                        }
                    })
                }
            })

        }else if(event == 'journalTable'){//查看日志
            layer.open({
                type:2,
                title:"商品操作日志",
                area:['100%','100%'],
                scrollbar: false,
                offset:'auto',
                btn:["确定","取消"],
                content:"/product/log/productLog/product-log.html",
            })
        }else if(event == 'deleteTable'){//删除商品
            layer.confirm('确认要删除吗?', {icon: 3, title:'提示'}, function(index){
                var productId = obj.data.productId;
                var param = {
                    'tableName':'js_product',
                    'type':3,
                    'userId':userId,
                    'remark':'删除反馈统计',
                    'logType':1,
                };
                //添加操作日志
                $.ajax({
                    url:"/product/addProductLog",
                    type:'post',
                    dataType:'json',
                    data:param,
                    success:function (data) {
                    }
                });
                //删除商品
                $.ajax({
                    url:"/product/deleteProduct",
                    type:'post',
                    dataType:'json',
                    data:{'id':productId},
                    success:function (data) {
                    }
                });
                //删除商品审核
                $.ajax({
                    url:"/product/deleteProductRecord",
                    type:'post',
                    dataType:'json',
                    data:{'id':productId,'type':3},
                    success:function (data) {
                    }
                });
                //删除商品评论
                $.ajax({
                    url:"/product/deleteProductComment",
                    type:'post',
                    dataType:'json',
                    data:{'id':productId,'type':3},
                    success:function (data) {
                    }
                });
                layer.close(index);
                getTable('','','','');
            });
        }
    })
    //查看商品详情
    checkTable = function checkTable(id) {
        $.ajax({
            url: '/product/getProductInformation',
            type: 'post',
            dataType: 'json',
            data: {'type':3,'id':id},
            success: function (data) {
                localStorage.setItem('product',JSON.stringify(data.data));
                layer.open({
                    type:2,
                    title:"商品详情",
                    area:['95%','100%'],
                    Boolean:true,
                    maxmin:true,
                    closeBtn:1,
                    btn:["确定","取消"],
                    offset:['0px','35px'],
                    content:"product-details.html",
                    success: function (layero,index) {
                        layero.find('.layui-layer-max').remove();
                        layero.find('.layui-layer-min').remove();
                        var child = layero.find('iframe').contents();
                    }
                })
            }
        })
    };
    //返回
    $('#goBack').click(function () {
        parent.tabParentChange(3);
    })
    $(document).click(function () {
        parent.$('.rightMenu').hide();
    });
})